package com.aofeng.hybridwork.android.task;

import android.app.ProgressDialog;
import android.os.AsyncTask;

import com.aofeng.hybrid.activity.HybridActivity;
import com.aofeng.hybrid.orm.SqlHelper;
import com.aofeng.hybrid.service.RestService;
import com.aofeng.hybrid.util.CommUtil;
import com.aofeng.hybridwork.application.HybridApplication;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;

/**
 * 更新安检单审核情况异步任务
 * Created by LGY on 2016-08-25.
 */
public class RefreshPaperApprovalTask extends AsyncTask<String, String, Boolean> {
    private static final Logger log = LoggerFactory.getLogger(RefreshPaperApprovalTask.class);

    HybridActivity hybridActivity;

    public RefreshPaperApprovalTask(HybridActivity hybridActivity) {
        this.hybridActivity = hybridActivity;
    }

    @Override
    /**
     * params:
     * 计划id
     */
    protected Boolean doInBackground(String... params) {
        try {
            publishProgress(new String[]{ 0 + "", "开始更新......"});

            RestService rs = new RestService(hybridActivity);
            JSONObject joRequest = new JSONObject();
            joRequest.put("action", "post");
            joRequest.put("url", HybridApplication.SQL_SERVICE_URL + URLEncoder.encode("获取计划项审核状态", "UTF-8"));
            joRequest.put("data", "{\"data\":{\"f_plan_id\":\"" + params[0] + "\"}}");
            JSONArray array = (JSONArray) rs.execute(joRequest);

            publishProgress(new String[]{ 30 + "", "下载更新数据......"});

            int n = array.length();
            for(int i = 0; i < n; i++) {
                JSONObject jo = array.getJSONObject(i);
                SqlHelper.run(hybridActivity,
                        "update t_check_plan_item set "
                                + "f_approved = '" + jo.getString("f_approved") + "', "
                                + "f_approved_by='" + jo.getString("f_approved_by") + "', "
                                + "f_approved_time='" + jo.getString("f_approved_time") + "', "
                                + "f_approved_note='" + (jo.isNull("f_approved_note") ? "" :jo.getString("f_approved_note")) + "' "
                                + "where id = '" + jo.getString("id") + "' and (f_approved = '未审核' or f_approved='重检' or f_approved='打回')"
                );
                if(jo.getString("f_approved").equals("已审核")) {
                    updateApprovalState(jo);
                    //打回
                } else {
                    // 查找本地安检单，看是否已经审核
                    JSONObject paper = FetchPaperTask.getPaper(jo.getString("id"), CommUtil.getSharedPreference(hybridActivity, "f_user_id"), hybridActivity);
                    // 没审核则更新状态和图片
                    if (paper.getString("f_approved").equals("未审核") || paper.getString("f_approved").equals("重检")) {
                        updatePicPaths(paper);
                        updateApprovalState(jo);
                    }
                }
                publishProgress(new String[]{ (30 + (i*70)/n ) + "", "更新计划项" + i + "/" + n});
            }

            publishProgress(new String[]{ 100 + "", "更新完成。"});
            return true;
        } catch(Exception e) {
            return false;
        }
    }

    //修改照片的名称
    private void updatePicPaths(JSONObject paper) throws Exception{
        HashMap<String, String> defects = collectDefects(paper.getJSONArray("f_defects"));
        doUpdatePicPath(paper, "t_check_paper", defects);
        doUpdatePicPath(paper.getJSONArray("f_furnaces"), "t_check_paper_furnace", defects);
        doUpdatePicPath(paper.getJSONArray("f_heaters"), "t_check_paper_heater", defects);
        doUpdatePicPath(paper.getJSONArray("f_alarms"), "t_check_paper_alarm", defects);
        doUpdatePicPath(paper.getJSONArray("f_cookers"), "t_check_paper_cooker", defects);
        doUpdatePicPath(paper.getJSONArray("f_inner_plumbs"), "t_check_paper_innerplumb", defects);
        doUpdatePicPath(paper.getJSONArray("f_valves"), "t_check_paper_valve", defects);
        doUpdatePicPath(paper.getJSONArray("f_plumbs"), "t_check_paper_plumb", defects);
        doUpdatePicPath(paper.getJSONArray("f_meters"), "t_check_paper_meter", defects);
        //不处理f_defects
    }

    /**
     * 得到所有的隐患照片
     * @param f_defects
     * @return
     */
    private HashMap<String,String> collectDefects(JSONArray f_defects) throws Exception{
        HashMap<String, String> hm = new HashMap<String, String>();
        for(int i=0; i<f_defects.length(); i++) {
            JSONObject jo = f_defects.getJSONObject(i);
            if(jo.has("f_defect_path") && !jo.isNull("f_defect_path")) {
                String fileName = jo.getString("f_defect_path");
                int end = fileName.indexOf("?");
                if(end == -1)
                    end = fileName.length();
                fileName = fileName.substring(0, end);
                hm.put(fileName, jo.getString("id"));
            }
        }
        return hm;
    }

    private void doUpdatePicPath(JSONObject jo, String tableName, HashMap defects)  throws  Exception{
        //查找所有的path属性，如果不为空，得到文件名
        //修改文件名，更新数据库
        Iterator<String> itr = jo.keys();
        String sql = "update " + tableName + " set id = id ";
        while(itr.hasNext()) {
            String col = itr.next();
            if(col.endsWith("_path")) {
                if(!jo.isNull(col) && jo.getString(col).length() != 0 && !jo.getString(col).endsWith("nopic.png")) {
                    String fileName = jo.getString(col);
                    int start = fileName.indexOf("-");
                    if(start == -1)
                        start = fileName.lastIndexOf("/") + 1;
                    int end = fileName.indexOf("?");
                    if(end == -1)
                        end = fileName.length();
                    String oldFullName = fileName.substring(0, end);
                    int slash = fileName.lastIndexOf("/");
                    String newFullName = fileName.substring(0, slash+1) + UUID.randomUUID().toString().replace("-", "") + fileName.substring(start, end);

                    //更新隐患表
                    if(defects.containsKey(oldFullName)) {
                        SqlHelper.run(hybridActivity, "update t_check_paper_defect set f_defect_path = '" + newFullName + "' where id='" + defects.get(oldFullName) + "'");
                    }
                    //修改文件名
                    File oldFile = new File(oldFullName.substring(0,slash+1).substring(7), oldFullName.substring(slash+1));
                    File newFile = new File(newFullName.substring(0,slash+1).substring(7), newFullName.substring(slash+1));
                    boolean succeed = oldFile.renameTo(newFile);
                    log.debug("oldFile:" + oldFullName + "\nnewFile:" + newFullName + "\nrenamed:" + succeed);

                    sql += ", " + col + " = '" + newFullName  + "'";
                }
            }
        }

        //更新数据库
        sql += " where id='" + jo.getString("id") + "'";
        SqlHelper.run(hybridActivity, sql);
    }

    private void doUpdatePicPath(JSONArray array, String tableName, HashMap defects) throws  Exception{
        for(int i=0; i<array.length(); i++) {
            doUpdatePicPath(array.getJSONObject(i), tableName, defects);
        }
    }

    private void updateApprovalState(JSONObject jo) throws Exception {
        SqlHelper.run(hybridActivity,
                "update t_check_paper set "
                        + "f_approved = '" + jo.getString("f_approved") + "', "
                        + "f_approved_by='" + jo.getString("f_approved_by") + "', "
                        + "f_approved_time='" + jo.getString("f_approved_time") + "', "
                        + "f_approved_note='" + (jo.isNull("f_approved_note") ? "" : jo.getString("f_approved_note")) + "' "
                        + "where f_check_item_id = '" + jo.getString("id") + "' and (f_approved = '未审核' or f_approved='重检' or f_approved='打回')"
        );
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        hybridActivity.createProgressDialog(ProgressDialog.STYLE_SPINNER);
    }

    @Override
    protected void onPostExecute(Boolean flag) {
        super.onPostExecute(flag);
        hybridActivity.closeProgress();
        hybridActivity.mWebView.loadUrl("javascript:HostApp.__callback__(" + flag + ");");
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        int progress = Integer.parseInt(values[0]);
        hybridActivity.setProgress(progress, values[1]);
    }
}
